﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Atomic.Db;
using Atomic.User.Entities;
using NHibernate.Linq;
using Atomic.Common;
using Atomic.Common.Validators;
using Atomic.User.DAL;
using NHibernate;

#region 版本信息
/*********************************************
 * 作者：杜一博
 * 创建日期：2012/8/1 23:02:55
 *********************************************
 * 修改：
 * 修改日期：
 * 修改说明：
 *********************************************/
#endregion

namespace Atomic.User.BLL
{
    /// <summary>
    /// UserBll 描述内容
    /// </summary>
    public class UserBLL : ErrorImpl, IUser
    {
        /// <summary>
        /// 添加新的用户信息：先添加基本信息，再添加扩展信息 
        /// </summary>
        /// <param name="entity">用户基础信息</param>
        /// <returns>是否添加用户信息成功</returns>
        public virtual bool Add(UserBaseEntity entity)
        {
            //实体验证
            if (!(VResult = entity.Validate()).Success)
            {
                Error = new ErrorResult()
                {
                    Message = VResult.FailureMessage
                };
                return false;
            }

            using (ISession session = HibernateHelper.GetSession())
            {
                UserBaseDAL userBaseDAL = new UserBaseDAL(session);
                //存在同登录名的用户，则返回
                if (userBaseDAL.Exist(m => m.LoginName.Equals(entity.LoginName)))
                {
                    Error = new ErrorResult()
                    {
                        Message = string.Format("用户名已存在")
                    };
                    return false;
                }
                //开启事务添加用户信息
                session.BeginTransaction();
                try
                {
                    userBaseDAL.Add(entity);    //添加用户基本信息
                    userBaseDAL.AddExtendData(entity.ExtendData, entity.TypeID, entity.ID);  //添加扩展信息 
                    session.Transaction.Commit();   //提交事务
                }
                catch (Exception ex)
                {
                    session.Transaction.Rollback();
                    throw new Exception("添加新用户信息引发异常", ex);
                }
            }
            return true;
        }

        /// <summary>
        /// 更新用户信息：先更新基础信息，再更新扩展表信息；
        /// 如果密码为空，则不更新密码
        /// </summary>
        /// <param name="entity">用户信息</param>
        /// <param name="userID">用户ID</param>
        /// <returns>是否更新成功</returns>
        public virtual bool Update(UserBaseEntity entity, int userID)
        {
            //实体验证
            if (!(VResult = entity.Validate(new List<string> { UserBaseEntity.PASSWORD }, false)).Success)
            {
                Error = new ErrorResult()
                {
                    Message = VResult.FailureMessage
                };
                return false;
            }

            using (ISession session = HibernateHelper.GetSession())
            {
                UserBaseDAL userBaseDAL = new UserBaseDAL(session);
                UserBaseEntity tmpEntity = userBaseDAL.Get(userID);
                if (tmpEntity == null)
                {
                    Error = new ErrorResult()
                    {
                        Message = "找不到要更新的用户信息"
                    };
                    return false;
                }
                //开启事务添加用户信息
                session.BeginTransaction();
                try
                {
                    entity.Password = string.IsNullOrEmpty(entity.Password) ? entity.Password : tmpEntity.Password; //密码为空，则保留原始密码
                    userBaseDAL.Update(entity, userID); //更新基本信息
                    userBaseDAL.UpdateExtendData(entity.ExtendData, tmpEntity.TypeID, tmpEntity.ID);  //更新扩展信息 
                    session.Transaction.Commit();   //提交事务
                }
                catch (Exception ex)
                {
                    session.Transaction.Rollback();
                    throw new Exception("添加新用户信息引发异常", ex);
                }
            }
            return true;
        }

        /// <summary>
        /// 删除用户基础，同时删除扩展信息
        /// </summary>
        /// <param name="userID">用户ID</param>
        /// <returns>是否删除成功</returns>
        public virtual bool Remove(int userID)
        {
            using (ISession session = HibernateHelper.GetSession())
            {
                UserBaseDAL userBaseDAL = new UserBaseDAL(session);
                UserBaseEntity tmpEntity = userBaseDAL.Get(userID);
                if (tmpEntity == null)
                {
                    Error = new ErrorResult()
                    {
                        Message = "找不到要删除的用户信息"
                    };
                    return false;
                }
                //开启事务
                session.BeginTransaction();
                try
                {
                    userBaseDAL.Remove(tmpEntity.ID);   //删除用户基础信息
                    userBaseDAL.RemoveExtendData(tmpEntity.TypeID, tmpEntity.ID);  //删除扩展信息 
                    session.Transaction.Commit();   //提交事务
                }
                catch (Exception ex)
                {
                    throw new Exception("删除用户信息引发异常", ex);
                }
                finally
                {
                    if (session.Transaction.IsActive)
                    {
                        session.Transaction.Rollback();
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// 按ID查询用户
        /// </summary>
        /// <param name="userID">用户ID</param>
        /// <returns>用户信息</returns>
        public virtual UserBaseEntity Get(int userID)
        {
            UserBaseDAL userBaseDAL = new UserBaseDAL();
            UserBaseEntity entity = userBaseDAL.Get(userID);
            return entity;
        }

        /// <summary>
        /// 按登录名查询用户
        /// </summary>
        /// <param name="loginName">登录名</param>
        /// <returns>用户信息</returns>
        public virtual UserBaseEntity Get(string loginName)
        {
            UserBaseDAL userBaseDAL = new UserBaseDAL();
            UserBaseEntity entity = userBaseDAL.Get(m => m.LoginName.Equals(loginName));
            return entity;
        }

        /// <summary>
        /// 增加一种新的用户类型，同时创建用户类型对应的数据表
        /// </summary>
        /// <param name="entity">用户类型实体</param>
        /// <returns>是否添加成功</returns>
        public virtual bool AddType(UserTypeEntity entity)
        {
            //实体验证
            if (!(VResult = entity.Validate()).Success)
            {
                Error = new ErrorResult()
                {
                    Message = VResult.FailureMessage
                };
                return false;
            }

            UserTypeDAL userTypeDAL = new UserTypeDAL();
            //已经存在的用户类型或用户名称
            if (userTypeDAL.Exist(m => m.ID.Equals(entity.ID)
                || m.Name.Equals(entity.Name)))
            {
                Error = new ErrorResult()
                {
                    Message = "用户类型或用户名称已经存在"
                };
                return false;
            }
            else
            {
                using (ISession session = HibernateHelper.GetSession())
                {
                    session.BeginTransaction();
                    try
                    {
                        userTypeDAL.Add(entity);    //新建用户类型
                        userTypeDAL.CreateUserExtendTable(entity.ID);   //创建用户类型对应的表
                        session.Transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("创建新的用户类型引发异常", ex);
                    }
                    finally
                    {
                        if (session.Transaction.IsActive)
                        {
                            session.Transaction.Rollback(); //回滚业务
                        }
                    }
                }
                return true;
            }
        }

        /// <summary>
        /// 更新类型信息
        /// </summary>
        /// <param name="entity">新对象</param>
        /// <param name="id">待更新的对象的ID</param>
        /// <returns>是否更新成功</returns>
        public virtual bool UpdateType(UserTypeEntity entity, int id)
        {
            //实体验证
            if (!(VResult = entity.Validate()).Success)
            {
                Error = new ErrorResult()
                {
                    Message = VResult.FailureMessage
                };
                return false;
            }

            UserTypeDAL userTypeDAL = new UserTypeDAL();
            UserTypeEntity existType = userTypeDAL.GetList(m => m.Name.Equals(entity.Name))
                .FirstOrDefault();  //查询是否存在相同名称的类型
            //新名称与数据库已经存在相同名称，返回提示信息
            if (existType != null //已经存在相同名称类型
                && existType.ID != entity.ID) //且相同名称类型的不是自己
            {
                Error = new ErrorResult()
                {
                    Message = "已存在相同类型名称"
                };
                return false;
            }
            else
            {
                userTypeDAL.Update(entity, id);
                return true;
            }
        }

        /// <summary>
        /// 获取指定用户类型详细信息
        /// </summary>
        /// <param name="id">用户类型ID</param>
        /// <returns>用户类型详细信息</returns>
        public virtual UserTypeEntity GetType(int id)
        {
            UserTypeDAL userTypeDAL = new UserTypeDAL();
            return userTypeDAL.Get(id);
        }

        /// <summary>
        /// 查询所有有效用户类型信息
        /// </summary>
        /// <returns>有效用户类型列表</returns>
        public virtual List<UserTypeEntity> GetTypes()
        {
            UserTypeDAL userTypeDAL = new UserTypeDAL();
            return userTypeDAL.GetList();
        }

        /// <summary>
        /// 删除用户类型，同时删除用户类型对应的数据表，存在对应类型的用户的情况下，禁止删除
        /// </summary>
        /// <param name="id">用户类型ID</param>
        /// <returns>是否删除成功</returns>
        public virtual bool RemoveType(int id)
        {
            using (ISession session = HibernateHelper.GetSession())
            {
                UserBaseDAL userBaseDAL = new UserBaseDAL(session);
                if (userBaseDAL.Exist(m => m.TypeID == id))
                {
                    Error = new ErrorResult()
                    {
                        Message = "存在该类型的用户信息，禁止删除"
                    };
                    return false;
                }
                //开启事务
                session.BeginTransaction();
                try
                {
                    UserTypeDAL userTypeDAL = new UserTypeDAL(session);
                    userTypeDAL.Remove(id); //删除类型记录
                    userTypeDAL.DropUserExtendTable(id);    //删除类型对应的表
                    session.Transaction.Commit();
                }
                catch (Exception ex)
                {
                    throw new Exception("删除用户类型引发异常", ex);
                }
                finally
                {
                    if (session.Transaction.IsActive)
                    {
                        session.Transaction.Rollback(); //回滚业务
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// 添加新的用户类型对应的字段信息，同时在用户类型对应的表中增加新的字段列
        /// </summary>
        /// <param name="fieldEntity">新字段</param>
        /// <returns>是否添加成功</returns>
        public virtual bool AddProperty(UserExtendFieldEntity fieldEntity)
        {
            //实体验证
            if (!(VResult = fieldEntity.Validate()).Success)
            {
                Error = new ErrorResult()
                {
                    Message = VResult.FailureMessage
                };
                return false;
            }

            using (ISession session = HibernateHelper.GetSession())
            {
                UserExtendFieldDAL userExtendFieldDAL = new UserExtendFieldDAL(session);
                //如果指定类型的用户已经存在该字段，则写入提示信息，并返回
                if (userExtendFieldDAL.Exist(m => m.UserTypeID == fieldEntity.UserTypeID
                    && m.Name.Equals(fieldEntity.Name)))
                {
                    Error = new ErrorResult()
                    {
                        Message = "已经存在同名字段"
                    };
                    return false;
                }
                //开启事务
                session.BeginTransaction();
                try
                {
                    userExtendFieldDAL.Add(fieldEntity);    //添加字段信息到记录表
                    userExtendFieldDAL.AddUserExtendField(fieldEntity); //添加新的字段列到用户类型对应的扩展表
                    session.Transaction.Commit();
                }
                catch (Exception ex)
                {
                    throw new Exception("添加新的用户信息扩展字段异常", ex);
                }
                finally
                {
                    if (session.Transaction.IsActive)
                    {
                        session.Transaction.Rollback(); //回滚业务
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// 修改字段显示名称、长度、备注，不能直接修改其他属性，只能删除后重新添加字段
        /// </summary>
        /// <param name="fieldEntity">修改字段信息</param>
        /// <param name="id">字段ID</param>
        /// <returns>是否修改成功</returns>
        public virtual bool UpdateProperty(UserExtendFieldEntity fieldEntity, int id)
        {
            //实体验证
            if (!(VResult = fieldEntity.Validate(new List<string>() 
            { 
                UserExtendFieldEntity.DISPLAY_NAME, //显示名称
                UserExtendFieldEntity.COMMENT,  //备注信息
                UserExtendFieldEntity.LENGTH,    //长度
                UserExtendFieldEntity.FIELD_TYPE    //字段类型
            }, true)).Success)
            {
                Error = new ErrorResult()
                {
                    Message = VResult.FailureMessage
                };
                return false;
            }

            using (ISession session = HibernateHelper.GetSession())
            {
                UserExtendFieldDAL userExtendFieldDAL = new UserExtendFieldDAL(session);
                //开启事务
                session.BeginTransaction();
                try
                {
                    userExtendFieldDAL.Update(fieldEntity, id);
                    userExtendFieldDAL.UpdateUserExtendField(fieldEntity);
                    session.Transaction.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    throw new Exception("更新的用户信息扩展字段异常", ex);
                }
                finally
                {
                    if (session.Transaction.IsActive)
                    {
                        session.Transaction.Rollback(); //回滚业务
                    }
                }
            }
        }

        /// <summary>
        /// 删除用户扩展属性字段
        /// </summary>
        /// <param name="id">扩展属性字段ID</param>
        /// <returns>是否删除成功</returns>
        public virtual bool RemoveProperty(int id)
        {
            using (ISession session = HibernateHelper.GetSession())
            {
                UserExtendFieldDAL userExtendFieldDAL = new UserExtendFieldDAL(session);
                UserExtendFieldEntity entity = userExtendFieldDAL.Get(id);
                //存在字段信息
                if (entity != null)
                {
                    //所有记录中，该字段是否为空
                    if (!userExtendFieldDAL.IsFieldValueEmpty(entity.UserTypeID, entity.Name))
                    {
                        Error = new ErrorResult()
                        {
                            Message = "字段已经在使用中,禁止删除"
                        };
                        return false;
                    }
                    try
                    {

                        //开启事务
                        session.BeginTransaction();
                        userExtendFieldDAL.Remove(id);    //删除用户类型扩展属性
                        userExtendFieldDAL.DropUserExtendField(entity.UserTypeID, entity.Name); //删除用户类型扩展表字段
                        session.Transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        session.Transaction.Rollback();
                        throw new Exception("删除用户扩展表字段异常", ex);
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// 按用户类型查询该类型扩展属性信息
        /// </summary>
        /// <param name="userTypeID">用户类型</param>
        /// <returns>扩展属性列表</returns>
        public virtual List<UserExtendFieldEntity> GetExtendPropertiesByUserType(int userTypeID)
        {
            UserExtendFieldDAL userExtendFieldDAL = new UserExtendFieldDAL();
            return userExtendFieldDAL.GetList(m => m.UserTypeID == userTypeID);
        }
    }
}
